// pages/luoAn/device/LocationChoice.js
const app = getApp()
const appkey = "MLCBZ-QUCYO-MAHWW-S7ZTA-G6IR2-AZFM5";
const {
  QQMapWX,
  LuoAnHttp
} = app.globalData;
var qqmapsdk = new QQMapWX({
  key: appkey
});
const marker = {
  latitude: 22.55329,
  longitude: 113.88308,
  title: '',
  width: 18,
  height: 24,
  iconPath: '/img/common/location_icon.png',
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '定位ing...',
    latitude: 22.55329,
    longitude: 113.88308,
    searchResult: [],
    key: '',
    clickItem: {
      ...marker
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.locationPress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  reverGeo: function (param) {
    return new Promise((relove, reject) => {
      qqmapsdk.reverseGeocoder({
        location: param,
        success: s => {
          console.log('解析结果',s)
          relove && relove(s.result)
        },
        fail: f => {
          reject && reject(f)
        }
      })
    })
  },
  locationPress: async function () {
    const location = await this.location()
    console.log('location',location)
    if (location == null) {
      wx.showModal({
        title: '提示',
        content: '定位权限未开启,请打开',
        success: res => {
          if (res.confirm) {
            wx.openSetting({
              withSubscriptions: true,
            })
          } else if (res.cancel) {
            wx.openSetting({
              withSubscriptions: true,
            })
          }
        },
      })
      return
    }
    const res = await this.reverGeo(location)
    this.setData({
      longitude: location.longitude,
      latitude: location.latitude,
      clickItem: {
        ...marker,
        longitude: location.longitude,
        latitude: location.latitude,
        title:res.address
      },
      key:'',
      address: res.address
    })
  },
  submitBtnPress:async function () {
     
    const eventChannel = this.getOpenerEventChannel();
    const param = {
      ...this.data,
      longitudeandlatitude: `${this.data.clickItem.longitude},${this.data.clickItem.latitude}`,
      deviceposition:this.data.address,
    }
    eventChannel && eventChannel.emit && eventChannel.emit('callback', param)
  },
  location: function (e) {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        altitude: false,
        success: e => resolve({
          longitude: e.longitude,
          latitude: e.latitude
        }),
        fail: f => resolve(null)
      })
    })
  },
  markersTap:async function(e){
    this.setData({
      address: await this.reverGeo({longitude:this.data.clickItem.longitude,latitude:this.data.clickItem.latitude}).address
    })
  },
  popMethod: function (e) {
    let pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack();
    } else {
      wx.reLaunch({
        url: '/pages/luoAn/device/deviceIndex',
      })
    }
  },
  bindconfirm: async function () {
    // const res = await this.searchMap(this.data.key)
    // this.setData({
    //   searchResult: res
    // })
  },
  bindinput:function (e) {
    const key = e.detail.value
    if(key.length>0){
      this.getSuggestion(key);
    }else{
      this.setData({searchResult:[]})
    } 
  },
  getSuggestion:function(key){
    const _that = this;
    const param = {
      keyword:key,
    }
    console.log("pram",param)
    qqmapsdk.getSuggestion({
      ...param,
      success:s=>_that.setData({searchResult:s.data,key:key}),
      fail:f=>console.log(f)
    })
  },



  searchMap: function (key) {
     
    return new Promise((resolve, reject) => {
      qqmapsdk.search({
        keyword: key,
        success: s => {
          resolve(s.data)
          console.log(s)
        },
        fail: f => {
          resolve([])
          console.log(f)
        }
      })
    })
  },
  onClick: async function (e) {
    const item = e.currentTarget.dataset.model
    const innerMarker = {...marker,latitude:item.location.lat,longitude:item.location.lng,title:item.title}
    console.log('innerMarker',innerMarker);
    let result = await this.reverGeo({latitude:innerMarker.latitude,
      longitude:innerMarker.longitude});
    console.log('address',result.address);
    this.setData({
      clickItem: innerMarker,
      latitude:innerMarker.latitude,
      longitude:innerMarker.longitude,
      address:result.address,
      key:item.title,
      searchResult: []
    })
  },
  mapBindtap:async function(e){
    const res = await this.reverGeo({...e.detail})
     
    this.setData({
      address:res.address,
      clickItem:{...marker,...e.detail,title:res.address}
    })
  }
})